/*
 * Copyright (c) 2014 - 2016. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.myself;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.danlu.lib.net.update.DownloadTaskDelegate;
import com.danlu.lib.net.update.UpgradeProxy;
import com.tbruyelle.rxpermissions.RxPermissions;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.AgentUtils;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.PreferenceUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.request.mydl.version.AppVersionCompareRequest;
import cn.com.hd.mall.web.webservices.entity.response.mydl.version.AppVersionCompareResponse;
import cn.com.hd.mall.web.webservices.entity.utils.DanluConstants;
import rx.Subscriber;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * author: 李一方(<a href="mailto: liyifang@danlu.com"> liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-12-22 10:04<br/>
 *
 * <p>
 * 我的丹露---关于丹露页面
 * </p>
 */
public class AboutDanluActivity extends BaseActivity {
    /**
     * apk更新地址
     */
    public static String URL = "";
    /**
     * 最新版本号
     */
    public static String LATEST_VERSION = "";
    /**
     * 是否更新
     */
    private TextView txtIsUpdate;
    /**
     * 是否更新
     */
    private Button btnClickUpdate;
    /**
     * 存储用共同类
     */
    private PreferenceUtils preferenceUtils;
    private PackageInfo packageInfo;

    private boolean isForceUpdate;


    /**
     * 丹露用异步任务代理
     */
    // private DanluTaskProxy danluTaskProxy;
    @SuppressLint("SetTextI18n")
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        // 初始化界面
        setContentView (R.layout.activity_about_danlu);

        @SuppressLint("HardwareIds")
        String devId = Secure.getString (getContentResolver (), Secure.ANDROID_ID);
        preferenceUtils = new PreferenceUtils (this, devId);

        btnClickUpdate = (Button) findViewById (R.id.clickUpdate);
        txtIsUpdate = (TextView) findViewById (R.id.txtIsLastestVersion);
        // 版本信息
        TextView tvVersionInfo = (TextView) findViewById (R.id.txtVersionInfo);
        // 客户热线
        TextView tvCallPhone = (TextView) findViewById (R.id.txtCallPhone);
        if (packageInfo == null) {
            packageInfo = AgentUtils.getPackageInfo (AboutDanluActivity.this);
        }
        tvVersionInfo.setText (getResources ().getString (R.string.myself_version_pre) + packageInfo.versionName); //版本号
        getVersion ();

        if (btnClickUpdate != null) {
            btnClickUpdate.setOnClickListener (new View.OnClickListener () {

                @Override
                public void onClick (View arg0) {
                    // 下载apk
                    if (DownloadTaskDelegate.newInstance ().isDownloading ()) {
                        ToastUtil.getInstance ().show (R.string.apk_downloading);
                        return;
                    }
                    startDownload ();
                }
            });
        }
        if (tvCallPhone != null) {
            tvCallPhone.setOnClickListener (new View.OnClickListener () {
                @Override
                public void onClick (View v) {
                    // 直接拨打电话 | 打开拨号界面 此处直接拨打电话
                    new ViewDialog.Builder (AboutDanluActivity.this)
                            .setTitle (getString (R.string.call_phone_hint))
                            .setMessage (getString (R.string.myself_abort_danlu_tel_num))
                            .setNegativeButton (R.string.btn_cancel, new DialogInterface.OnClickListener () {
                                @Override
                                public void onClick (DialogInterface dialog, int which) {
                                    dialog.dismiss ();
                                }
                            })
                            .setPositiveButton (R.string.btn_confirm, new DialogInterface.OnClickListener () {
                                @Override
                                public void onClick (DialogInterface dialog, int which) {
                                    CommonUtils.callHelp (AboutDanluActivity.this);
                                    dialog.dismiss ();
                                }
                            }).create ().show ();
                }
            });
        }
    }

    @Override
    protected String getActivityTitle () {
        return null;
    }

    /**
     * 返回前画面，画面有特殊需求复写该方法
     */
    protected void back () {
        // 返回前画面
        finish ();
    }

    /**
     * 获取版本信息
     */
    private void getVersion () {
        // 请求版本信息
        AppVersionCompareRequest request = new AppVersionCompareRequest ();
        request.setToken (agent.getToken ());
        request.setClientVersion (preferenceUtils.getVersion ());
        request.setOsCode (DanluConstants.Constants.OS_CODE);
        request.setEquipmentCode (DanluConstants.Constants.EQUIPMENT_CODE);
        request.setAppType (DanluConstants.Constants.APP_TYPE_0);
        agent.getApi ().getVersion (request).compose (OperatorUtils.<AppVersionCompareResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<AppVersionCompareResponse> (AboutDanluActivity.this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess (AppVersionCompareResponse appVersionCompareResponse) {
                        if (appVersionCompareResponse.getClientObsoleted ().equals ("1")) {
                            URL = appVersionCompareResponse.getDownloadUrl ();// 获取apk下载url
                            LATEST_VERSION = appVersionCompareResponse.getLatestVersion ();
                            isLastestVersion (LATEST_VERSION);// 是否是最新版本
                            isForceUpdate = appVersionCompareResponse.getForceUpgrade ().equals ("1");
                        } else {
                            btnClickUpdate.setVisibility (View.GONE);
                            txtIsUpdate.setText (getResources ().getString (R.string.version_is_newest));
                        }
                    }

                    @Override
                    protected String parseBussinessException (String code) {
                        txtIsUpdate.setText (getResources ().getString (R.string.version_is_newest));
                        return "";
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        if (!TextUtils.isEmpty (displayMessage)) {
                            ToastUtil.getInstance ().show (displayMessage);
                        }
                    }
                });
    }

    private void startDownload () {
        RxPermissions rxPermissions = new RxPermissions (this);
        rxPermissions.request (Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe (new Subscriber<Boolean> () {
                    @Override
                    public void onCompleted () {

                    }

                    @Override
                    public void onError (Throwable e) {

                    }

                    @Override
                    public void onNext (Boolean granted) {
                        if (granted) {
                            download ();
                        } else {
                            ToastUtil.getInstance ().show ("下载写入文件权限被拒绝");
                        }
                    }
                });
    }

    private void download () {
        String baseUrl = URL.substring (0, URL.lastIndexOf ("/") + 1);
        String downloadUrl = URL.substring (URL.lastIndexOf ("/") + 1, URL.length ());
        UpgradeProxy.Builder builder = new UpgradeProxy.Builder ()
                .baseUrl (baseUrl)
                .downloadUrl (downloadUrl)
                .apkVersion (LATEST_VERSION)
                .apkMD5 (null)
                .contentTitle (getString (R.string.app_name))
                .context (this)
                .notificationSmallIcon (R.mipmap.ic_launcher)
                .isForceUpdate (isForceUpdate)
                .interactionType (isForceUpdate ? UpgradeProxy.InteractionType.both : UpgradeProxy.InteractionType.notificationbar);
        DownloadTaskDelegate.newInstance ().downloadApk (builder);
    }

    /**
     * 判断是否是最新版本
     */
    private void isLastestVersion (String newVersion) {
        if (TextUtils.isEmpty (newVersion) || newVersion.equals (packageInfo.versionName)) {
            txtIsUpdate.setText (getResources ().getString (R.string.myself_lastest_version));
            btnClickUpdate.setVisibility (View.GONE);
        } else {
            txtIsUpdate.setText (getResources ().getString (R.string.myself_has_new_version));
            btnClickUpdate.setVisibility (View.VISIBLE);
        }
    }

}